package com.accountant.travelaccountant;

import java.util.ArrayList;
import java.util.Arrays;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddMember extends Activity {

	protected static final int PICK_CONTACT = 0;
	EditText etTitle, input;
	AutoCompleteTextView etAddMember;
	Spinner spnSuggestMembers;
	ArrayAdapter<String> adpSuggestMembersAdapter;
	Button btnFinish, btnAddMember, btnUpdate, btnDelete, btnSuggestMembers,
			btnAddDateTime;
	ArrayList<String> memberList, arrSuggestMembersAdapter;
	DatabaseOperations_NonActivity databaseOperations;
	ArrayAdapter<String> adapterForMembers;
	Addmember_ListviewAdapter addmember_ListviewAdapter;
	ListView listViewForAddMember;
	AddMember addMember;
	/* For maintaining the list of columns */
	String[] columns;
	/* For maintaining the list of attributes for the columns */
	ArrayList<String> attributes = new ArrayList<String>();
	TextView editDetails;
	String memberToBeReplaced, titleToBeReplaced;
	AlertDialog alertDialog;
	static boolean firstTimeSelected;
	Uri contactData;
	private static int noOfTimesBackButtonPressed = 0;
	ArrayList<String> listOfNames;
	int toBreak = 0;
	int length = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_member);
		addMember = this;
		/* Setting it true so that listener is not called by default */
		firstTimeSelected = true;

		/* Setting the text to null */
		Addmember_ListviewAdapter.setTitletextOfSelectedTextview(null);

		/* Initializing the listview */
		memberList = new ArrayList<String>();
		listViewForAddMember = (ListView) findViewById(R.id.listViewForAddmember);
		addmember_ListviewAdapter = new Addmember_ListviewAdapter(addMember,
				memberList);
		listViewForAddMember.setAdapter(addmember_ListviewAdapter);

		/* Creating an object of DatabaseOperations to access its functions */
		databaseOperations = new DatabaseOperations_NonActivity(this);

		/* Initialising the controls with their id's */
		etTitle = (EditText) findViewById(R.id.etTitle);
		etAddMember = (AutoCompleteTextView) findViewById(R.id.etAddMember);
		btnAddMember = (Button) findViewById(R.id.btnAddMember);
		btnFinish = (Button) findViewById(R.id.btnFinish);
		btnUpdate = (Button) findViewById(R.id.btnUpdate);
		btnDelete = (Button) findViewById(R.id.btnDelete);
		editDetails = (TextView) findViewById(R.id.editDetails);
		btnSuggestMembers = (Button) findViewById(R.id.btnSuggestMembers);
		btnAddDateTime = (Button) findViewById(R.id.addDateTime);
		
		databaseOperations.openWriteableDatabase();
		listOfNames = databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getUniquenamestable(),
				new String[] { DatabaseOperations_NonActivity
						.getUniquenamestablenames() }, null, null, null, null,
				null);
		/*Setting the adapter for the dropdown list of etAddmember*/
		adapterForMembers=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listOfNames);
		etAddMember.setAdapter(adapterForMembers);
		etAddMember.setDropDownVerticalOffset(10);
		etAddMember.setTextColor(Color.BLACK);
		/* Close the database */
		databaseOperations.closeDatabase();

		/*
		 * Every time this activity is loaded the array list should be
		 * Initialised
		 */
		memberList = new ArrayList<String>();

		addmember_ListviewAdapter = new Addmember_ListviewAdapter(addMember,
				memberList);
		listViewForAddMember.setAdapter(addmember_ListviewAdapter);

		/* Have to keep the Update delete and spinner for member list invisible */
		makeInvisible();

		btnAddMember.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				addMember();
			}
		});

		btnFinish.setOnClickListener(new OnClickListener() {

			@SuppressLint("ShowToast")
			@Override
			public void onClick(View v) {
				finishAddingMembers();
			}
		});

		btnDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				deleteAMember();
			}
		});

		btnUpdate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialogBoxUpdateMember("Rename the member", "Enter the name");
			}
		});

		btnSuggestMembers.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getNamesfromPhoneContactList();
			}
		});

		btnAddDateTime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialogBoxAddDateTime("Add Date and Time",
						"Do you want to add date and time with the account name");
			}
		});

		listViewForAddMember.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				v.getParent().getParent().getParent()
						.requestDisallowInterceptTouchEvent(true);
				return false;

			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		String name = "";
		try {
			switch (requestCode) {
			case PICK_CONTACT:
				if (resultCode == Activity.RESULT_OK)
					contactData = data.getData();
				Cursor c = getContentResolver().query(contactData, null, null,
						null, null);
				if (c.moveToFirst()) {
					name = c.getString(c
							.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				}
				break;
			}
		} catch (Exception e) {

		}

		etAddMember.setText(name);
	}

	/* Adding a date and time in account */
	private void showDialogBoxAddDateTime(String title, String message) {
		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);

		dialogBuilder.setPositiveButton("Add",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						if (etTitle.getText().length() == 0) {
							etTitle.setText(Utils_NotActivity.getCurrentDate()
									+ " at "
									+ Utils_NotActivity.getCurrentTime());
						} else {
							titleToBeReplaced = etTitle.getText().toString()
									.replaceAll("\\s+", " ");
							titleToBeReplaced = titleToBeReplaced + " : "
									+ Utils_NotActivity.getCurrentDate()
									+ " at "
									+ Utils_NotActivity.getCurrentTime();
							etTitle.setText(titleToBeReplaced);
						}
						/* Set cursor at the end */
						etTitle.setSelection(etTitle.getText().length());
					}
				});
		dialogBuilder.setNegativeButton("Don't Add",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

		alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	/* Dialog box for suggesting the members to the user */
	@SuppressWarnings("unused")
	private void showDialogBoxSuggestMember(String title, String message) {
		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);

		/* Creating the spinner for the dialog box */
		spnSuggestMembers = new Spinner(this);
		arrSuggestMembersAdapter = new ArrayList<String>(
				Arrays.asList("Select"));
		/* Opening the database */
		databaseOperations.openWriteableDatabase();
		/* Retrieving only distinct columns from member table */
		arrSuggestMembersAdapter.addAll(databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getMembertable(),
				new String[] { DatabaseOperations_NonActivity
						.getMembertablemember() }, null, null,
				DatabaseOperations_NonActivity.getMembertablemember(), null,
				null));
		/* Closing the database */
		databaseOperations.closeDatabase();
		adpSuggestMembersAdapter = new ArrayAdapter<String>(
				getApplicationContext(), android.R.layout.simple_spinner_item,
				arrSuggestMembersAdapter);
		spnSuggestMembers.setAdapter(adpSuggestMembersAdapter);
		/******************************************/

		/* Adding the spinner to the dialog box */
		dialogBuilder.setView(spnSuggestMembers);

		spnSuggestMembers
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {

						/*
						 * For the first time it is not selected but the moment
						 * anything is selected it happens
						 */
						if (firstTimeSelected == false) {

							if (!spnSuggestMembers.getSelectedItem().toString()
									.equalsIgnoreCase("select")) {
								/* Checking if the member already exists */
								if (memberList.contains(spnSuggestMembers
										.getSelectedItem().toString())) {
									Toast.makeText(getApplicationContext(),
											"Member already added",
											Toast.LENGTH_SHORT).show();
								} else {
									/* Adding to the arraylist */
									memberList.add(spnSuggestMembers
											.getSelectedItem().toString());
									Toast.makeText(
											getApplicationContext(),
											spnSuggestMembers.getSelectedItem()
													.toString()
													+ " is added as a member",
											Toast.LENGTH_SHORT).show();
									/* Function to make the controls visible */
									makeVisible(memberList);
								}
								firstTimeSelected = true;
								alertDialog.dismiss();
							}
						} else
							firstTimeSelected = false;

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});

		alertDialog = dialogBuilder.create();
		alertDialog.show();

	}

	/* Dialog box for Updating a member in the spinner */
	private void showDialogBoxUpdateMember(String title, String message) {
		/* Check for the account being selected or not */
		if (checkIfAnyAccountHasBeenSelectedOrNot()) {
			return;
		}
		/* Storing the member in a string */
		memberToBeReplaced = Addmember_ListviewAdapter
				.getTitletextOfSelectedTextview();

		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);

		input = new EditText(this);
		input.setSingleLine();
		input.setText(memberToBeReplaced);
		/* Function to put the cursor at the last */
		Utils_NotActivity.setCursorPosition(input);
		dialogBuilder.setView(input);

		/* Adding an event listener for changing text */
		input.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Utils_NotActivity.validateTextLength(input);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		dialogBuilder.setPositiveButton("Rename",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						/* In case the name is to changed then he can do it */
						memberList.add(input.getText().toString()
								.replaceAll("\\s+", " ").trim());
						/* Showing a pop up for renaming */
						if (!input.getText().toString().replaceAll("\\s+", " ")
								.trim().equals(memberToBeReplaced)) {
							Toast.makeText(
									getApplicationContext(),
									memberToBeReplaced
											+ " was renamed to "
											+ input.getText().toString()
													.replaceAll("\\s+", " ")
													.trim(), Toast.LENGTH_SHORT)
									.show();
						} else {
							Toast.makeText(getApplicationContext(),
									"Same name was not renamed",
									Toast.LENGTH_SHORT).show();
						}
						memberList.remove(memberToBeReplaced);


						/*
						 * Assigning the adapter to a spinner so that spinner
						 * shows arraylist of strings
						 */
						addmember_ListviewAdapter = new Addmember_ListviewAdapter(
								addMember, memberList);
						listViewForAddMember
								.setAdapter(addmember_ListviewAdapter);
						Addmember_ListviewAdapter
								.setTitletextOfSelectedTextview(null);
					}
				});

		dialogBuilder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						return;
					}
				});

		AlertDialog alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	public void displayArrayList(ArrayList<String> arr) {

		if (arr == null)
			Toast.makeText(getApplicationContext(), "Nothing in The database",
					Toast.LENGTH_SHORT).show();
		else {
			for (String str : arr) {
				Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT)
						.show();
			}
		}
	}

	/* To make the controls invisible */
	public void makeInvisible() {
		btnUpdate.setVisibility(View.GONE);
		btnDelete.setVisibility(View.GONE);
		// spnMemberList.setVisibility(View.GONE);
		listViewForAddMember.setVisibility(View.GONE);
		editDetails.setVisibility(View.GONE);
	}

	public void makeVisible(ArrayList<String> memberList) {
		/*
		 * Have to make the Update delete and spinner for member list Visible
		 * the moment the size increases
		 */
		// spnMemberList.setAdapter(adapter);

		addmember_ListviewAdapter = new Addmember_ListviewAdapter(addMember,
				memberList);
		listViewForAddMember.setAdapter(addmember_ListviewAdapter);
		listViewForAddMember.setVisibility(View.VISIBLE);
		btnUpdate.setVisibility(View.VISIBLE);
		btnDelete.setVisibility(View.VISIBLE);
		// spnMemberList.setVisibility(View.VISIBLE);
		editDetails.setVisibility(View.VISIBLE);
	}

	private void addMember() {
		/* Open the database */
		databaseOperations.openWriteableDatabase();

		/* Validation if both text boxes are empty */
		if (etTitle.getText().toString().equals("")
				&& etAddMember.getText().equals("")) {
			Toast.makeText(getApplicationContext(),
					"Both fields cannot be empty", Toast.LENGTH_SHORT).show();
			/* Closing the database */
			databaseOperations.closeDatabase();
			return;
		}
		/* Validation for title textbox */
		if (etTitle.getText().toString().equals("")) {
			Toast.makeText(getApplicationContext(),
					"Title field cannot be empty", Toast.LENGTH_SHORT).show();
			/* Closing the database */
			databaseOperations.closeDatabase();
			return;
		}
		/* Validation for Addmember textbox */
		if (etAddMember.getText().toString().equals("")) {
			Toast.makeText(getApplicationContext(),
					"Member field cannot be empty", Toast.LENGTH_SHORT).show();
			/* Closing the database */
			databaseOperations.closeDatabase();
			return;
		}

		/* preparing the set of columns */
		columns = new String[] {
				DatabaseOperations_NonActivity.getAmounttabletitle(),
				DatabaseOperations_NonActivity.getAmounttableamount() };

		/* Preparing the where statement */
		String whereStatement = DatabaseOperations_NonActivity
				.getAmounttabletitle()
				+ "="
				+ "\'"
				+ etTitle.getText().toString() + "\'";

		/* Check if the title already exists */
		if (databaseOperations.retrieve(
				DatabaseOperations_NonActivity.getAmounttable(), columns,
				whereStatement, null, null, null, null) != null) {
			Toast.makeText(getApplicationContext(), "Title Already Exists",
					Toast.LENGTH_SHORT).show();
			/* Closing the database */
			databaseOperations.closeDatabase();
			return;
		}

		/* Checking if the member already exists */
		if (memberList.contains(etAddMember.getText().toString()
				.replaceAll("\\s+", " ").trim())) {
			Toast.makeText(getApplicationContext(), "Member already added",
					Toast.LENGTH_SHORT).show();
		} else {
			/* Adding to the arraylist */
			memberList.add(etAddMember.getText().toString()
					.replaceAll("\\s+", " ").trim());
			/* So adding a pop up */
			Toast.makeText(
					getApplicationContext(),
					etAddMember.getText().toString().replaceAll("\\s+", " ")
							.trim()
							+ " is added as a member", Toast.LENGTH_SHORT)
					.show();
			/* Refreshing the Add member textbox */
			etAddMember.setText("");

			/* Function to make the controls visible */
			makeVisible(memberList);

		}

		/* Closing the database */
		databaseOperations.closeDatabase();
	}

	private void finishAddingMembers() {
		/* Open the database */
		databaseOperations.openWriteableDatabase();

		/* Validation for title textbox */
		if (etTitle.getText().toString().equals("")) {
			Toast.makeText(getApplicationContext(),
					"Title field cannot be empty", Toast.LENGTH_SHORT).show();
			/* Closing the database */
			databaseOperations.closeDatabase();
			return;
		}

		/* Validation for Addmember textbox */
		if (memberList.size() == 0
				&& etAddMember.getText().toString().equals("")) {
			Toast.makeText(getApplicationContext(),
					"You have not added any member to the account",
					Toast.LENGTH_SHORT).show();
			/* Closing the database */
			databaseOperations.closeDatabase();
			return;

		}

		/* preparing the set of columns */
		columns = new String[] {
				DatabaseOperations_NonActivity.getAmounttabletitle(),
				DatabaseOperations_NonActivity.getAmounttableamount(),
				DatabaseOperations_NonActivity.getAmounttabletotalmembers() };

		/* Preparing the where statement */
		String whereStatement = DatabaseOperations_NonActivity
				.getAmounttabletitle()
				+ "="
				+ "\'"
				+ etTitle.getText().toString() + "\'";

		/* Check if the title already exists */
		if (databaseOperations.retrieve(
				DatabaseOperations_NonActivity.getAmounttable(), columns,
				whereStatement, null, null, null, null) != null) {
			Toast.makeText(getApplicationContext(), "Title Already Exists",
					Toast.LENGTH_SHORT).show();
			/* Closing the database */
			databaseOperations.closeDatabase();
			return;
		}
		/*
		 * Case Where the last member is to be added but Add member is not used
		 * but finished is used
		 */
		/* But first if the member already added */
		if (memberList.contains(etAddMember.getText().toString()
				.replaceAll("\\s+", " ").trim())) {
			Toast.makeText(getApplicationContext(), "Member already added",
					Toast.LENGTH_SHORT).show();
			databaseOperations.closeDatabase();
		} else {
			/* Adding to the arraylist */
			if (!etAddMember.getText().toString().equals(""))
				memberList.add(etAddMember.getText().toString()
						.replaceAll("\\s+", " ").trim());

			/* Inserting into the AmountTable */
			/****************************************************/
			/* Creating the column list */
			columns = new String[] {
					DatabaseOperations_NonActivity.getAmounttabletitle(),
					DatabaseOperations_NonActivity.getAmounttableamount(),
					DatabaseOperations_NonActivity.getAmounttabletotalmembers() };

			/* For the attributes */
			/* For the Title column */
			attributes.add(etTitle.getText().toString().replaceAll("\\s+", " ")
					.trim());
			/* For the amount column */
			attributes.add(String.valueOf(0));
			/* For the size column */
			attributes.add(String.valueOf(memberList.size()));

			databaseOperations.insertIntoTable(
					DatabaseOperations_NonActivity.getAmounttable(), columns,
					attributes);

			attributes = new ArrayList<String>();
			/*******************************************************/

			/* Inserting into the Member Table */
			/****************************************************/
			/* Creating the column list */
			columns = new String[] {
					DatabaseOperations_NonActivity.getMembertabletitle(),
					DatabaseOperations_NonActivity.getMembertablemember() };

			/* For the attributes */
			attributes.add(etTitle.getText().toString());

			/* Message to show that the message ended */
			Toast.makeText(
					addMember.getApplicationContext(),
					"Account " + etTitle.getText().toString()
							+ " has been added", Toast.LENGTH_SHORT).show();

			for (String str : memberList) {
				attributes.add(str);
				databaseOperations.insertIntoTable(
						DatabaseOperations_NonActivity.getMembertable(),
						columns, attributes);
				/* Inserting into the uniquetable database too */
				databaseOperations.insertIntoTable(
						DatabaseOperations_NonActivity.getUniquenamestable(),
						Utils_NotActivity.uniqueNamesTableColumns(),
						new ArrayList<String>(Arrays.asList(str)));
				attributes.remove(attributes.size() - 1);
			}

			/* Refreshing the attribute list */
			attributes = new ArrayList<String>();
			/*******************************************************/

			/* Refreshing both the textboxes */
			etTitle.setText("");
			etAddMember.setText("");
			/* Refreshing the arraylist */
			memberList = new ArrayList<String>();
			/* refreshing the attribute list */
			attributes = new ArrayList<String>();
			/* So that it goes back to the front screen */
			/* Close the database */
			databaseOperations.closeDatabase();

			finish();
		}
	}

	private void deleteAMember() {
		/* Check for the account being selected or not */
		if (checkIfAnyAccountHasBeenSelectedOrNot()) {
			return;
		}
		/* Getting the member selected */
		String item = Addmember_ListviewAdapter
				.getTitletextOfSelectedTextview();
		/* Removing the member */
		memberList.remove(item);
		/* Assigning the new member list to the spinner */
		addmember_ListviewAdapter = new Addmember_ListviewAdapter(addMember,
				memberList);
		listViewForAddMember.setAdapter(addmember_ListviewAdapter);
		/* Making the contorls invisible in case the size is 0 */
		if (memberList.size() == 0) {
			makeInvisible();
		}
	}

	private void getNamesfromPhoneContactList() {
		/*
		 * Create an intent so that we go to the contacts list in the phone and
		 * get a contact
		 */
		Intent intent = new Intent(Intent.ACTION_PICK,
				ContactsContract.Contacts.CONTENT_URI);
		startActivityForResult(intent, PICK_CONTACT);
		// showDialogBoxSuggestMember("Add earlier added members", "");
	}

	@Override
	public void onBackPressed() {
		setNoOfTimesPressed(getNoOfTimesPressed() + 1);

		if (getNoOfTimesPressed() > 1) {
			finish();
			setNoOfTimesPressed(0);
		} else {
			Toast.makeText(getApplicationContext(), "Press again to exit",
					Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		setNoOfTimesPressed(0);
	}

	public static int getNoOfTimesPressed() {
		return noOfTimesBackButtonPressed;
	}

	public static void setNoOfTimesPressed(int noOfTimesPressed) {
		AddMember.noOfTimesBackButtonPressed = noOfTimesPressed;
	}

	/* A function to check whether the account was selected or not */
	private boolean checkIfAnyAccountHasBeenSelectedOrNot() {
		if (Addmember_ListviewAdapter.getTitletextOfSelectedTextview() == null) {
			Toast.makeText(getApplicationContext(), "No Member Selected",
					Toast.LENGTH_SHORT).show();
			return true;
		}
		return false;
	}

}
